package com.dhcc.httpserver;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import javax.print.attribute.standard.RequestingUserName;

import com.dhcc.util.CloseUtil;
import com.dhcc.util.Space;
import com.sun.corba.se.impl.oa.poa.ActiveObjectMap.Key;

public class Request {
	//请求方式
	private String method;
	//请求资源
	private String url;
	//请求参数
	private Map<String, List<String>> parameterMapValues;
	
	private String requestInfo;
	
	private InputStream is;
	
	private Request(){
		
		method = "";
		url = "";
		parameterMapValues = new HashMap<String,List<String>>();
		requestInfo="";
	}
	
	public Request(InputStream is){
		this();
		this.is=is;
		byte[] data = new byte[20480];
		try {
			int len = is.read(data);
			
			
			
			
			if(len == -1){
				
				CloseUtil.closeAll(is);
				return;
			}
			requestInfo = new String(data, 0, len);
			
		} catch (IOException e) {
			return;
		}
		//分析头信息
		parseRequestInfo();
		
	}

	/**
	 * 分析请求头
	 */
	private void parseRequestInfo() {
		
		//请求头为空不用分析了
		if (null==requestInfo||(requestInfo=requestInfo.trim()).equals("")) {
			return;
		}
		
		System.out.println(requestInfo);
		
		String firstLine = requestInfo.substring(0,requestInfo.indexOf(Space.CRLF));
		int index = firstLine.indexOf("/");
		this.method = firstLine.substring(0, index).trim();
		String urlStr = firstLine.substring(index,requestInfo.indexOf("HTTP/")).trim();
		String paramString = "";
		if(this.method.equalsIgnoreCase("post")){
			
			this.url=urlStr;
			paramString=requestInfo.substring(requestInfo.lastIndexOf(Space.CRLF)).trim();
		}else if(this.method.equalsIgnoreCase("get")){
			if (urlStr.contains("?")) {  //是否存在参数
				
				String[] urlArray = urlStr.split("\\?");
				this.url=urlArray[0];
				paramString=urlArray[1];
			}else{
				
				this.url=urlStr;
			}
		}
		
		
		//不存在请求参数
		if (paramString.equals("")) {
			return;
		}
		//2.将请求参数封装到Map中
		parseParams(paramString);
		
	}

	private void parseParams(String paramString) {
		
		StringTokenizer token = new StringTokenizer(paramString, "&");
		while(token.hasMoreTokens()){
			
			String keyValue = token.nextToken();
			String[] keyValues = keyValue.split("=");
			if (keyValues.length==1) {
				keyValues = Arrays.copyOf(keyValues, 2);
				keyValues[1] = null;
			}
			
			//转成map
			String key = keyValues[0].trim();
			String value=keyValues[1]==null?null:decode(keyValues[1], "utf-8");
			if (!parameterMapValues.containsKey(key)) {
				parameterMapValues.put(key, new ArrayList<String>());
			}
			
			List<String> values = parameterMapValues.get(key);
			values.add(value);
		}
		
		
	}
	
	/**
	 * 根据页面的Name 获取对应的多个值
	 * @param name
	 * @return
	 */
	public String[] getParameterValues(String name){
		
		List<String> values = null;
		if ( (values=parameterMapValues.get(name))==null) {
			return null;
		}else {
			return values.toArray(new String[0]);
		}
		
		
	}
	
	/**
	 * 根据页面的Name获取对应的单个值
	 * @param name
	 * @return
	 */
	public String getParameter(String name){
		
		String[] values = getParameterValues(name);
		if (null==values) {
			return null;
		}
		return values[0];
	}
	
	/**
	 * 对中文进行解码
	 * @param value
	 * @param code
	 * @return
	 */
	private String decode(String value,String code){
		
		try {
			return URLDecoder.decode(value,code);
		} catch (UnsupportedEncodingException e) {
			
		}
		return null;
	}

	public String getUrl() {
		return url;
	}
	
	

}
